import mime from "mime";
import { getExtName, isNotEmpty } from "jsmethod-extra";

export enum FileSuffix {
  HTML = "html",
  CSS = "css",
  JS = "js",
  PNG = "png",
  JPG = "jpg",
  JPEG = "jpeg",
  handleCommon = "handleCommon",
}

/**
 * @author lihh
 * @description 处理响应的类
 */
export class HandleResponse {
  private static instance: HandleResponse;

  static getInstance() {
    if (isNotEmpty(HandleResponse.instance)) {
      return HandleResponse.instance;
    }
    return (HandleResponse.instance = new HandleResponse());
  }

  public async handle(response: Response, filePathOrName: string) {
    const fileSuffix = getExtName(filePathOrName) as FileSuffix;

    if (isNotEmpty(this[fileSuffix])) {
      return await this[fileSuffix](response, filePathOrName);
    } else {
      return await this[FileSuffix.handleCommon](response, filePathOrName);
    }
  }

  private async [FileSuffix.handleCommon](
    response: Response,
    filePathOrName: string
  ) {
    // 先克隆
    const cloneResponse = response.clone();
    return new Response(cloneResponse.body, {
      status: cloneResponse.status,
      statusText: cloneResponse.statusText,
      headers: {
        "Content-Type": mime.getType(filePathOrName)!,
      },
    });
  }

  private async [FileSuffix.CSS](response: Response, filePathOrName: string) {
    return await this[FileSuffix.handleCommon](response, filePathOrName);
  }

  private async [FileSuffix.HTML](response: Response, filePathOrName: string) {
    return await this[FileSuffix.handleCommon](response, filePathOrName);
  }

  private async [FileSuffix.JS](response: Response, filePathOrName: string) {
    return await this[FileSuffix.handleCommon](response, filePathOrName);
  }

  private async [FileSuffix.PNG](response: Response, filePathOrName: string) {
    return await this[FileSuffix.handleCommon](response, filePathOrName);
  }

  private async [FileSuffix.JPEG](response: Response, filePathOrName: string) {
    return await this[FileSuffix.handleCommon](response, filePathOrName);
  }

  private async [FileSuffix.JPG](response: Response, filePathOrName: string) {
    return await this[FileSuffix.handleCommon](response, filePathOrName);
  }
}
